<?php

$content_width = 500;

/**
 * Settings -> Miscellaneous -> Medium size
 */
if ( get_option('medium_size_h') != $content_width ||  get_option('medium_size_w') != $content_width ) : 
	update_option('medium_size_h', $content_width);
	update_option('medium_size_w', $content_width);
endif;

if ( function_exists('register_sidebars') )
    register_sidebars( 2, array(
        'before_widget' => '<li id="%1$s" class="widget %2$s">',
        'after_widget' => '</li>',
        'before_title' => '<h2 class="widgettitle">',
        'after_title' => '</h2>',
    ));
    
$types = array(
	'text',
	'photo',
	'quote',
	'link',
	'chat',
	'video'
	); 

$options = (array) get_option('tumblelog');

function theme_init() {
	if ( is_admin() ) {
		add_action('admin_menu', 'theme_menu');
		add_action('admin_menu', 'post_menu');

		// install
		$options = get_option('tumblelog');
		
		if ( !is_array($options) ) {
			$defaults = array(
				'text' => '0',
				'photo' => '0', 
				'quote' => '0',
				'link' => '0',
				'chat' => '0',
				'video' => '0'
				);
			
			foreach ( $defaults as $name => $value )
				if ( !isset($options[$name]) )
					$options[$name] = $value;
		
			add_option('tumblelog', $options);
			add_action('admin_notices', 'theme_warning');			
		}
	}	
		
	if ( $_GET['page'] == 'theme-options' && isset($_POST['uninstall']) ) {
		// uninstall
		global $wpdb;
	
		delete_option('tumblelog');
		switch_theme('default', 'default');
		wp_cache_flush();
		
		wp_redirect('themes.php?activated=true');
		exit();
	}
}

add_action('init', 'theme_init');

function theme_warning() {
	echo "<div class='updated' style='background-color:#f66;'><p><a href='themes.php?page=theme-options'>tumblelog theme</a> needs attention: please assign a unique category to each type of post or deactivate the theme.</p></div>";
}

function theme_menu() {
	add_theme_page('Theme Options', 'Theme Options', 'edit_themes', 'theme-options', 'theme_options');
}

function theme_options() {
	include(TEMPLATEPATH . '/includes/options.php');
}

function post_menu() {
	global $types, $options;

	foreach ( $types as $type ) {
		if ( $type != 'text' && ($options[$type]) != '0' ) {
			add_submenu_page(
						'post-new.php'
						, 'Add ' . ucwords($type)
						, ucwords($type)
						, 1
						, $type
						, 'post_form'
			);
		}
	}		
}

function post_form() {
	include(TEMPLATEPATH . '/includes/post.php');	
}

function body_class($print = true) {
	global $wp_query;
		
	$c = array('hfeed');

	is_front_page() ? $c[] = 'home'       : null;
	is_home()       ? $c[] = 'blog'       : null;
	is_archive()    ? $c[] = 'archive'    : null;
	is_date()       ? $c[] = 'date'       : null;
	is_search()     ? $c[] = 'search'     : null;
	is_paged()      ? $c[] = 'paged'      : null;
	is_attachment() ? $c[] = 'attachment' : null;
	is_404()        ? $c[] = 'four04'     : null;

	if ( have_posts() ) {
		if ( is_single() ) {		
			the_post();
			$c[] = 'single';
	
			if ( is_attachment() ) {
				$mime_type = get_post_mime_type();
				$mime_prefix = array( 'application/', 'image/', 'text/', 'audio/', 'video/', 'music/' );
					$c[] = 'attachment-' . str_replace( $mime_prefix, "", "$mime_type" );
			}
	
			$c[] = 'author-' . sanitize_title_with_dashes(strtolower(get_the_author_login()));
			rewind_posts();
		}
	
		elseif ( is_author() ) {
			$author = $wp_query->get_queried_object();
			$c[] = 'author';
			$c[] = 'author-' . $author->user_nicename;
		}

		elseif ( is_category() ) {
			$cat = $wp_query->get_queried_object();
			$c[] = 'category';
			$c[] = 'category-' . $cat->slug;
		}
	
		elseif ( is_tag() ) {
			$tags = $wp_query->get_queried_object();
			$c[] = 'tag';
			$c[] = 'tag-' . $tags->slug;
		}
	
		elseif ( is_page() ) {
			$pageID = $wp_query->post->ID;
			$page_children = wp_list_pages("child_of=$pageID&echo=0");
			the_post();
			$c[] = 'page';
			$c[] = 'page-author-' . sanitize_title_with_dashes(strtolower(get_the_author('login')));

			if ( $page_children != '' )
				$c[] = 'page-parent';
			if ( $wp_query->post->post_parent )
				$c[] = 'page-child parent-pageid-' . $wp_query->post->post_parent;
			if ( is_page_template() )
				$c[] = 'page-template page-template-' . str_replace( '.php', '-php', get_post_meta( $pageID, '_wp_page_template', true ) );
			rewind_posts();
		}
	}
	
	elseif ( !is_404() ) {
		$c[] = 'four04';
	}
	
	if ( is_user_logged_in() )
		$c[] = 'loggedin';
		
	$c = join(' ', apply_filters('body_class',  $c));
	
	return $print ? print($c) : $c;
}

function post_class($print = true) {
	global $types, $options;
	
	$post = get_post($post_id);

	$c = array();

	$c[] = $post->post_type;
	$c[] = 'hentry';
		
	if ( !is_page() ) {
		foreach ( $types as $type ) :
			switch ( true ):
				case in_category($options[$type]):
					$c[] = $type;
					break;
			endswitch;
		endforeach;

		if ( in_category($options['link']) )
			$c[] = 'xfolkentry';
	}	
	
	$c = join(' ', apply_filters('post_class',  $c));
	
	return $print ? print($c) : $c;	
}

/**
 * Loads custom Quicktags config 
 */
function load_scripts() {
	$template_url = get_bloginfo('template_url');
	
	if ( strpos($_SERVER['REQUEST_URI'], 'post-new.php?page=') ) {
		wp_print_scripts('quicktags');
		echo '<script src="'.$template_url.'/js/quicktags.config.js" type="text/javascript"></script>';
	}
}

add_action('admin_head', 'load_scripts');

/**
 * Custom post formatting
 */
function format_post($content) {
	global $options;
	
	switch ( true ) :
		case in_category($options['text']) :
			break;
			
		case in_category($options['photo']) :
			$content = preg_replace(array('|\r|', '|\n|', '|\t|'), '', $content); 			
			$a = '#<p><img(.*?) /></p>#s';
			$b = '<img\1 /> ';
			$c = '#<p><a(.*?)><img(.*?) /></a></p>#s';
			$d = '<a\1><img\2 /></a> ';		
			$content = preg_replace(array($a, $c), array($b, $d), $content);				
			$content = preg_replace_callback('#(<p>.*?</p>)+#',format_description, $content);
			break;
			
		case in_category($options['quote']) :
		case in_category($options['text']) :
			$content = preg_replace(array('|\r|', '|\n|', '|\t|'), '', $content); 
			$content = preg_replace('#<blockquote([^>]*)><p>(.*?)</blockquote>#s', '<blockquote\1><p>&ldquo;\2</blockquote>', $content);
			$content = preg_replace('#<p>\&mdash; (?:<cite>|)(.*?)(?:</cite>|)</p>#s', ' <p class="source">&mdash; <cite>\1</cite></p>', $content);
			break;
			
		case in_category($options['link']) :
			$content = preg_replace(array('|\r|', '|\n|', '|\t|'), '', $content); 
			
			if ( !is_feed() ) {
				$content = preg_replace('#<p><a(.*?)href="([^"]*.)"(.*?)>(.*?)</a><\/p>#s', '<span class="raquo">&raquo;</span> <a rel="bookmark nofollow" class="taggedlink"\1href="\2"\3>\4</a> ', $content);
			} else {
				$content = preg_replace('#<p><a(.*?)href="([^"]*.)"(.*?)>(.*?)</a><\/p>#s', '', $content);
			}
			
			$content = preg_replace_callback('#(<p>.*?</p>)+#', format_description, $content);
			break;
			
		case in_category($options['chat']) :
			$content = preg_replace(array('|<p>|', '|</p>|', '|<br />|'), '', $content);
			$lines = explode("\n", $content);			
			$i = 1;
			$chat .= '<ol>';
			foreach ( $lines as $line ) {
				if ( $line != '' ) {
					$class = ($i % 2) ? 'odd' : 'even';
					$line = wp_specialchars($line);
					
					$text = preg_replace('#^(\w+): ([^>]*)#s', '<cite>\1</cite>: <blockquote>\2</blockquote>', $line);
					$text = preg_replace('#&lt;(.*?)&gt; ([^>]*)#s', '<cite>&lt;\1&gt;</cite> <blockquote>\2</blockquote>', $text);
					
					if ( $line == $text )
						$text = '<blockquote>'.$line.'</blockquote>';
					
					$chat .= '<li class="'.$class.'">'.$text.'</li>';
					$i++;
				}
			}
			$chat .= '</ol>';		
			return $chat;
			break;
			
		case ( in_category($options['video']) && !is_feed() ) :
			$content = preg_replace(array('|\r|', '|\n|', '|\t|'), '', $content);
			$a = '#<p><object([^>]*)>(.*?)</object></p>#s';
			$b = '<object\1>\2</object> ';
			$c = '#<p><embed([^>]*)>(.*?)</embed></p>#s';
			$d = '<embed\1>\2</embed> ';			
			$content = preg_replace(array($a, $c), array($b, $d), $content);
			$content = preg_replace_callback('#(<p>.*?</p>)+#', format_description, $content);			
			break;
	endswitch;
	
	return $content;
}

add_filter('the_content', 'format_post');

function format_description($content) {
	return '<div class="description">'.$content[0].'</div>';
}

function format_rss_link($permalink) {
	global $options;

	if ( in_category($options['link']) ) {
		$content = get_the_content();
		$permalink = preg_replace('#<a(.*?)href="([^"]*.)"(.*?)>[^>]+</a>(?:[^>]+|)#s', '\2' , $content);
	}

	return $permalink;
}

add_filter('the_permalink_rss', 'format_rss_link');

/**
 * Hook text type category to Write Post if set
 */
function add_text_category() {
	global $options;
	
	if ( $options['text'] != '0' && !strpos($_SERVER['REQUEST_URI'], 'post.php') )
		echo '<input type="hidden" name="post_category[]" value="'.$options['text'].'" />';
}

add_action('edit_form_advanced', 'add_text_category');

/**
 * Remove Write Post, Write Page menu then redirect to our custom page
 */
function text_redirect() {
	global $options, $submenu;
	
	if ( $options['text'] == '0' )
		unset($submenu['post-new.php'][5]); // Write Post
		
	unset($submenu['post-new.php'][10]); // Write Page

	$url = $_SERVER['REQUEST_URI'];
	
	if ( preg_match('#admin.php\?page=#', $url) ) {
		$new = preg_replace('#admin.php\?page=.*?#', 'post-new.php?page=\1', $url);
		wp_redirect($new);
		exit();
	}
}

if ( !current_user_can('manage_options') ) {
	add_action('admin_head', 'text_redirect');
}

?>